package com.histone.grab_ticket.web;

import com.histone.grab_ticket.entity.ResultBean;
import com.histone.grab_ticket.entity.UserEntity;
import com.histone.grab_ticket.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class AuthController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResultBean register(@RequestBody UserEntity userEntity) throws Exception {
        // Check if username and password is null
        if (StringUtils.isEmpty(userEntity.getUsername()) ||
                StringUtils.isEmpty(userEntity.getPassword()))
            throw new NullPointerException("用户名或密码无效");

        // Check if the username is used
        if(userService.getUserByUsername(userEntity.getUsername()) != null)
            throw new Exception("Username is used!");

        // Create a person in ignite
        userService.save(userEntity);
        return new ResultBean("注册成功");
    }

    @GetMapping("login")
    public ResultBean login(String username, String password) throws Exception{
        // Check if username and password is null
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
            throw new NullPointerException("用户名或密码无效");

        UserEntity userEntity = userService.getUserByUsername(username);
        // Check if the user is exist and password is right
        if(userEntity == null || !password.equals(userEntity.getPassword())){
            throw new Exception("用户名或密码不正确");
        }

        // Create Twt token
        Date now = new Date();
        String jwtToken = Jwts.builder().setSubject(userEntity.getId()).setExpiration(new Date(now.getTime() + 7200000))
                .claim("roles", "member").setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "welldone").compact();

        return new ResultBean<String>("Bearer;" + jwtToken);
    }
}
